package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;



    @GetMapping("/findAll")
    public Result findAll(){
        // 获取数据
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        // 返回
        return Result.ok(seckillGoodsList);
    }

    // 根据skuId获取秒杀详情
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    //http://api.gmall.com/api/activity/seckill/auth/getSeckillSkuIdStr/46
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        // 获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        // 根据skuId获取秒杀对象
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        // 判断
        if(seckillGoods != null){
            // 判断是否在活动时间范围内 startTime currentTime endTime
            Date currentTime = new Date();
            if(DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime) &&
                DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                // 生成下单码
                String skuIdStr = MD5.encrypt(userId);
                // 将下单码返回给页面
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("获取下单码失败！");

    }

    // 下单控制器
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,HttpServletRequest request){
        // 获取用户通过url传递的获取下单码
        String skuIdStr = request.getParameter("skuIdStr");
        // 验证下单码：再次获取用户id
        String userId = AuthContextHolder.getUserId(request);
        // 校验下单码
        if(!skuIdStr.equals(MD5.encrypt(userId))){
            // 验证失败
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        // 校验状态位
        String status = (String) CacheHelper.get(skuId.toString());
        if(StringUtils.isEmpty(status)){
            // 校验失败
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }else if("1".equals(status)){
            // 有商品，可以秒杀
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);

            // 将这个对象放入mq中
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,MqConst.ROUTING_SECKILL_USER,userRecode);
            // 正常秒杀成功，应该减库存，在这个地方只是将用户的基本信息放入了mq
        }else {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }

        // 返回数据
        return Result.ok();
    }

    // /api/activity/seckill/auth/checkOrder/{skuId}
    // 检查秒杀状态
    @GetMapping("auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        // 获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        // 返回数据
        return seckillGoodsService.checkOrder(skuId, userId);
    }

    // 秒杀订单数据提供
    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        // 当前需要在后台存储detailArrayList，userAddressList totalNum totalAmount
        // 获取用户id
        String userId = AuthContextHolder.getUserId(request);
        // 获取收货地址列表
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        // 获取用户秒杀的商品， 然后将商品放入detailArrayList集合中
        // hget key field
        String seckillOrdersKey = RedisConst.SECKILL_ORDERS;
        OrderRecode orderRecode = (OrderRecode) redisTemplate.boundHashOps(seckillOrdersKey).get(userId);
        // 判断
        if(orderRecode == null){
            return Result.fail().message("获取预下单失败");
        }
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
        // 声明一个订单明细集合
        List<OrderDetail> detailArrayList = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        // 获取预下单的skuNum
        orderDetail.setSkuNum(orderRecode.getNum());
        detailArrayList.add(orderDetail);
        // 存储数据
        map.put("userAddressList",userAddressList);
        map.put("detailArrayList",detailArrayList);
        map.put("totalNum","1");
        // 如果可以秒杀多个商品
//        OrderInfo orderInfo = new OrderInfo();
//        orderInfo.setOrderDetailList(detailArrayList);
//        orderInfo.sumTotalAmount();
//        orderInfo.getTotalAmount();
        map.put("totalAmount",seckillGoods.getCostPrice());
        // 返回数据
        return Result.ok(map);
    }

    // 保存秒杀订单
    @PostMapping("auth/submitOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        // 获取到用户id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        // 调用方法
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        // 细节处理
        if(orderId == null){
            return Result.fail().message("秒杀下单失败");
        }
        // 做过预下单 删除对呀数据
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);
        // 保存真正订单数据 RedisConst.SECKILL_ORDERS_USERS
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId,orderId.toString());
        // 返回orderId
        return Result.ok(orderId);

    }
}
